<?php
/**
 * php_curl模块模拟客户端
 *
 * @param string $url     -------- 要提交的地址，如果是GET方式参数就放这边，如：xxx.xxx.xxx/xxx.xxx?xxx1=xxx1_value&xxx2=xxx2_value&...
 * @param string $data    -------- 如果是POST提交，才要这传入这个参数，
 * @return string
 */
function meclient($url='',$data='')
{
    if ($url == '') {
        return '';
    }
    $cksfile = 'cookie_file.txt';
    // 模拟提交数据函数
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
    //判断是不是https
    if (strpos($url,'https://') === 0) {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
    }

    //    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
    // curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);//HTTP请求User-Agent:头
    //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
    //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
    if ($data != '') {
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // Post提交的数据包
    }
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
//    curl_setopt($curl, CURLOPT_COOKIESESSION, 1);
    curl_setopt($curl, CURLOPT_COOKIEJAR, $cksfile); //读上次cookie
    curl_setopt($curl, CURLOPT_COOKIEFILE, $cksfile); //写本次cookie
    curl_setopt($curl, CURLOPT_TIMEOUT, 160); // 设置超时限制防止死循环
    curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
    $tmpInfo = curl_exec($curl); // 执行操作
    if (curl_errno($curl)) {
        echo 'Errno'.curl_error($curl);//捕抓异常
    }
//    preg_match_all('/Set-Cookie:(.*?)=(.*?);/is',$tmpInfo,$regs);
//print_r($regs);
    curl_close($curl); // 关闭CURL会话
    return $tmpInfo; // 返回数据
}

/**
 * 去掉无用字符
 *
 * @param string $str
 * @return string
 */
function remove_invalid($str)
{
	if ($str == '') {
		return $str;
	}
	$str = trim($str);
	$aTmp = array("\n","\r","\t","&nbsp;");
	$aReplace = array("","","","");
	$str = str_replace($aTmp,$aReplace,$str);
	return $str;
}

/**
 * 按时间大小排序
 *
 * @param array or string $e
 * @param string $str
 * @return array
 */
function array_intime_sort($e,$str='')
{
	$r = '';
	$lin_r = '';
	if (!is_array($e)) {
		$a_sorttmp = explode($e,$str);
	} else {
		$a_sorttmp = $e;
	}
	if (!empty($a_sorttmp)) {
		sort($a_sorttmp);
		$aTmp = array();
		foreach ($a_sorttmp as $a_sorttmp_v) {
			if (in_array($a_sorttmp_v,$aTmp)) {
				continue;
			}
			$aTmp[] = $a_sorttmp_v;
			if ($a_sorttmp_v <= '03:00') {
				$lin_r .= '&nbsp;'.$a_sorttmp_v;
				continue;
			}
			$r .= '&nbsp;'.$a_sorttmp_v;
		}
	}
	if ($r != '') {
		$r = substr($r,6).$lin_r;
	} elseif ($lin_r != '') {
		$r = substr($lin_r,6);
	}
	return $r;
}


/**
 * 合并电影名相同的数据
 *
 * @param array $aaP
 * @return array $aaResult
 */
function merge_result($aaP)
{
	$aaTmp = array();
	foreach ($aaP as $v) {
		if (array_key_exists($v['movie_name'],$aaTmp)) {
			$aaTmp[$v['movie_name']]['movie_time'] = array_merge($aaTmp[$v['movie_name']]['movie_time'], $v['movie_time']);
		} else {
			$aaTmp[$v['movie_name']] = $v;			
		}
	}
	$i = 0;
	$aaResult = array();
	if (!empty($aaTmp)) {
		foreach ($aaTmp as $v) {
			$aaResult[$i] = $v;
			$i++;
		}
	}
	return $aaResult;
}

/**
 * 返回指定的天数时间戳
 *
 * @param int $iNum
 * @return array
 */
function get_date($iNum=2)
{
	$aTmp = array();
	for ($i=0;$i<$iNum;$i++) {
		$iStamp = strtotime('+'.$i.' day');
		$aTmp[$i] = $iStamp;
	}
	return $aTmp;
}

/**
 * 采集出错处理
 *
 * @param unknown_type $sGoUrl
 * @param unknown_type $sCfile
 * @param unknown_type $sCline
 * @param unknown_type $aP
 * $sLogTheaterName === string 出错的采集的影院名
 * $sGoUrl === string 出错的采集数据的url
 * $sCfile === string 出错的脚本名
 * $sCline === string 出错的脚本中大概第几行
 * $aP['error_template']['con'] === string 错误信息模板
 * $aP['error_template']['search_replace'] === string 错误信息模板要替换的参数
 * $aP['log_email'] === string 调用邮件和日志的对象
 * $aP['logs_path'] === string 日志记录路径
 * $aP['isdie'] === bool 错误处理完之后是否结束掉程序
 * $sFringeMsg === string 附加的错误信息
 */
function gather_handle_error($sLogTheaterName,$sGoUrl,$sCfile,$sCline,$aP,$sFringeMsg='')
{
	$sMsg = str_replace($aP['error_template']['search_replace'],array($sLogTheaterName,$sGoUrl,$sCfile,$sCline),$aP['error_template']['con']);
	if ($sFringeMsg != '') {
		$sMsg .= '++++'.$sFringeMsg;
	}
	$aP['log_email']->sent_email($sMsg);
	$aP['log_email']->write_log($sMsg,$aP['logs_path']);
	if (isset($aP['isdie']) && $aP['isdie'] == true) {
		exit;
	}
}

/**
 * 得到用户传的参数
 *
 * @param string $aP 0=>'get',1=>'post',2=>'argv'---取参数顺序get-post-argv
 * @return unknown
 */
function get_parameter($aP=array('get','post','argv'))
{
	foreach ($aP as $v) {
		$sType = strtoupper($v);
		if ($sType == 'ARGV') {
			global $argv;
			$aTmp = $argv;
		} elseif ($sType == 'GET') {
			$aTmp = $_GET;
		} elseif ($sType == 'POST') {
			$aTmp = $_POST;
		}
		if (!empty($aTmp)) {
			foreach ($aTmp as $k=>$v) {
				$aR[$k] = $v;
			}
		}
	}
	return $aR;
}

function final_parameter($aIndex,$aParameter,$aCon)
{
	$aTmpHave = array();
	if (!isset($aParameter[$aIndex[0]]) || $aParameter[$aIndex[0]] == '') {
		if (isset($aParameter[$aIndex[1]]) && $aParameter[$aIndex[1]] != '') {
			$aParameter[$aIndex[0]] = $aParameter[$aIndex[1]];			
		}
	}
	if (isset($aParameter[$aIndex[0]]) && $aParameter[$aIndex[0]] != '') {
		$aTmp = explode(',',$aParameter[$aIndex[0]]);
		if ($aTmp) {
			foreach ($aTmp as $v) {
				if (!isset($aCon[$v])) {
					continue;
				}
				$aTmpHave[] = $aCon[$v];
			}
		}
	} else {
		$aTmpHave = $aCon;
	}
	if (empty($aTmpHave)) {
		show_error('参数有误,传which参数：“1,3,5”');
	}
	return $aTmpHave;
}

// 说明：PHP 中将全角字符转换成半角的方法
function sbc_dbc($str)
{
	$queue = Array(
	'０' => '0', '１' => '1', '２' => '2', '３' => '3', '４' => '4',
	'５' => '5', '６' => '6', '７' => '7', '８' => '8', '９' => '9',
	'Ａ' => 'A', 'Ｂ' => 'B', 'Ｃ' => 'C', 'Ｄ' => 'D', 'Ｅ' => 'E',
	'Ｆ' => 'F', 'Ｇ' => 'G', 'Ｈ' => 'H', 'Ｉ' => 'I', 'Ｊ' => 'J',
	'Ｋ' => 'K', 'Ｌ' => 'L', 'Ｍ' => 'M', 'Ｎ' => 'N', 'Ｏ' => 'O',
	'Ｐ' => 'P', 'Ｑ' => 'Q', 'Ｒ' => 'R', 'Ｓ' => 'S', 'Ｔ' => 'T',
	'Ｕ' => 'U', 'Ｖ' => 'V', 'Ｗ' => 'W', 'Ｘ' => 'X', 'Ｙ' => 'Y',
	'Ｚ' => 'Z', 'ａ' => 'a', 'ｂ' => 'b', 'ｃ' => 'c', 'ｄ' => 'd',
	'ｅ' => 'e', 'ｆ' => 'f', 'ｇ' => 'g', 'ｈ' => 'h', 'ｉ' => 'i',
	'ｊ' => 'j', 'ｋ' => 'k', 'ｌ' => 'l', 'ｍ' => 'm', 'ｎ' => 'n',
	'ｏ' => 'o', 'ｐ' => 'p', 'ｑ' => 'q', 'ｒ' => 'r', 'ｓ' => 's',
	'ｔ' => 't', 'ｕ' => 'u', 'ｖ' => 'v', 'ｗ' => 'w', 'ｘ' => 'x',
	'ｙ' => 'y', 'ｚ' => 'z', '－' => '-'
	);
	foreach ($queue as $k => $v) {
		$str = str_replace($k,$v,$str);
	}
	
	return $str;
} 

/**
 * 去掉（）【】《》()[]<>
 *
 * @param string $str
 * @return string
 */
function remove_noneed($str)
{
	if ($str == '') {
		return $str;
	}
	$str = trim($str);
	$aTmp = array("（","）","【","】","《","》","(",")","[","]","<",">");
	$aReplace = array("","","","","","","","","","","","");
	$str = str_replace($aTmp,$aReplace,$str);
	return $str;
}


/**
 * 计算中文字符串长度
 *
 * @param string $string
 * @return string
 */
function utf8_strlen($string = null)
{
	// 将字符串分解为单元
	preg_match_all("/./us", $string, $match);
	// 返回单元个数
	if (!isset($match[0])) {
		$sR = false;
	} else {
		$sR = count($match[0]);
	}
	return $sR;
}

/**
* 输出变量的内容，通常用于调试
*
* @package Core
*
* @param mixed $vars 要输出的变量
* @param string $label
* @param boolean $return
*/
function dump($vars, $label = '', $return = false)
{
    if (ini_get('html_errors')) {
        $content = "<pre>\n";
        if ($label != '') {
            $content .= "<strong>{$label} :</strong>\n";
        }
        $content .= htmlspecialchars(print_r($vars, true));
        $content .= "\n</pre>\n";
    } else {
        $content = $label . " :\n" . print_r($vars, true);
    }
    if ($return) { return $content; }
    echo show_msg($content);
    return null;
}

